<?php

namespace App\Http\Controllers\Back;

use App\Models\Note;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use Illuminate\Support\Facades\Storage;
use Illuminate\Support\Facades\Validator;

class NoteController extends BackController
{
    public function show()
    {

        $notes = Note::orderby('updated_at', 'desc')->paginate(12);
        return view('admin/note', compact('notes'));

    }

    public function addHtml()
    {
        return view("admin/noteadd");
    }

    public function noteadd(Request $request)
    {
        $validate = Validator::make($request->all(), [
            'title' => 'required',
            'pic' => 'required|image',
            'author' => 'required',
            'content' => 'required'
        ]);
        if ($validate->passes()) {
            $input = $request->except('_token');
            $path = Storage::putFile('note_photo', $request->file('pic'));
            $input['pic'] = $path;
            Note::create($input);
            return redirect('admin/note')->with('success', '添加成功!');
        }
        return redirect('admin/noteadd')
            ->withErrors($validate)
            ->withInput();
    }

    public function notedel($id)
    {
        $data = Note::find($id);
        $picPath = $data->pic;
        Storage::delete($picPath);
        $data->delete();
        return redirect('admin/note')->with('success', '删除成功！');
    }

    public function editHtml($id)
    {
        $note = Note::find($id);
        return view("admin/noteedit", compact('note'));

    }

    public function noteedit(Request $request)
    {
        $note = Note::FIND($request['id']);
        $validate = Validator::make($request->all(), [
            'title' => 'required',
            'pic' => 'image',
            'author' => 'required',
            'content' => 'required'
        ]);
        if ($validate->passes()) {
            $input = $request->except('_token', 'id');
            if ($request->file('pic')) {
                Storage::delete($note->pic);
                $path = Storage::putFile('note_photo', $request->file('pic'));
                $input['pic'] = $path;
            }
            $note->update($input);
            return redirect('admin/note');
        }
        return redirect('admin/noteedit/' . $request['id'])
            ->withErrors($validate)
            ->withInput();
    }
}
